package com.tencent.ncnnyolox.net;

/**
 * <pre>
 *     author : yh
 *     e-mail : xxx@xx
 *     time   : 2023/11/23
 *     desc   :
 * </pre>
 */
import android.util.Log;

import com.google.gson.Gson;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import java.io.IOException;

public class OkHttpClient {

   private okhttp3.OkHttpClient client = new okhttp3.OkHttpClient.Builder().addInterceptor(new LoggingInterceptor()).build();

   public void makePostRequest(String url, String authToken, String value,NetListener listener) {
      // 构建请求体
      RequestBody formBody = new FormBody.Builder()
              .add("model", "qwen-turbo") // 根据实际需求添加参数
              .add("input.prompt", value)
              .build();

      RequestBean requestBean=new RequestBean();
      requestBean.setModel("qwen-turbo");
      Input input=new Input();
      input.setPrompt(value);
      requestBean.setInput(input);

      String json=new Gson().toJson(requestBean);


      RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), json);
      // 构建请求对象
      Request request = new Request.Builder()
              .url(url)
              .header("Authorization",  authToken) // 添加Header，这里示例添加了一个Authorization头
              .post(requestBody) // 设置请求体
              .addHeader("Content-Type", "application/json")
              .build();


      // 异步调用
      client.newCall(request).enqueue(new Callback() {
         @Override
         public void onFailure(Call call, IOException e) {
            // 网络请求失败的处理
            e.printStackTrace();
         }

         @Override
         public void onResponse(Call call, Response response) throws IOException {
            // 网络请求成功的处理
            if (response.isSuccessful()) {
               // 获取响应体的字符串
               String responseBody = response.body().string();
               ResponseBean responseBean=new Gson().fromJson(responseBody,ResponseBean.class);
               listener.onSuccess(responseBean.getOutput().getText());
               // 在这里处理你的响应数据
               Log.d("OkHttpClient",responseBody);
            }else {
               Log.e("OkHttpClient",response.message());
            }
         }
      });
   }
}

